package com.lmh.job;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson2.JSONObject;
import com.lmh.bean.JobState;
import com.lmh.bean.OfflineAnalyticTemplate;
import com.lmh.utils.DataBasePoolUtil;
import com.lmh.utils.JedisUtil;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

@Slf4j
public class OfflineAnalyticJob implements Runnable{
    private OfflineAnalyticTemplate offlineAnalyticTemplate;
    private JobState jobStatus;
    public OfflineAnalyticJob(OfflineAnalyticTemplate offlineAnalyticTemplate){
        this.offlineAnalyticTemplate = offlineAnalyticTemplate;
        this.jobStatus = JobState.RUNNING;
    }

    public OfflineAnalyticTemplate getOfflineAnalyticTemplate() {
        return offlineAnalyticTemplate;
    }

    public void setOfflineAnalyticTemplate(OfflineAnalyticTemplate offlineAnalyticTemplate) {
        this.offlineAnalyticTemplate = offlineAnalyticTemplate;
    }

    public JobState getJobStatus() {
        return jobStatus;
    }

    public void setJobStatus(JobState jobStatus) {
        this.jobStatus = jobStatus;
    }

    /**
     * 获取执行参数
     */
    @Override
    public void run() {
        DruidPooledConnection connection = null;
        String executionParams = offlineAnalyticTemplate.getExecutionParams();
        String sqlContent = offlineAnalyticTemplate.getSqlContent();
        JSONObject param = JSONObject.parseObject(executionParams);
        String databaseType = param.getString("databaseType");
        log.info("即将执行离线分析sql：\n【" + sqlContent + "】");
        DruidDataSource dataSource = DataBasePoolUtil.getDataSource(databaseType);
        try {
            connection = dataSource.getConnection();
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(sqlContent);
            while (resultSet.next()){
//                装配返回参数
            }
            Jedis jedis = JedisUtil.getJedis();
            jedis.set("", "");
            jobStatus = JobState.FINISH;
        } catch (SQLException e) {
            jobStatus = JobState.DIED;
            e.printStackTrace();
        }finally {
            if(connection != null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
